/**
 * Company : Thai Informatic System Co., Ltd.
 * Created By : Dr.Tree
 * Created On : Feb 13, 2012  12:13:46 PM 
 * e-Mail : chatree@tis.co.th
 * Mobile Phone : (+66) 087-921-5115
 * Package Name : sap.business.mm.inbound
 * File Name : MmMatmasInbService.java
 * TODO
 */
package sap.business.mm.inbound;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import javax.persistence.EntityManager;

import jpa.entitys.promis.common.Company;
import jpa.entitys.promis.common.CostProject;
import jpa.entitys.synchro.common.ACTION_HANDLER;
import jpa.entitys.synchro.staging.MmMatmasInb;
import jpa.service.common.SessionEntityManager;
import jpa.service.synchro.staging.MmMatmasInbServices;

import org.apache.log4j.Logger;

import com.sap.mw.jco.JCO;

import promis.utility.CommonService;
import sap.business.commons.services.CommonJCOReturn;
import apps.promis.in.common.CompanyAction;
import apps.promis.in.common.CostArticleAction;
import apps.promis.in.common.ProjectAction;

/**
 * @author Chatree Siangklom of Administrator
 * Date =Nov 12, 2013 : 2:00:22 PM 
 * CreateBy=Chatree Siangklom
 * 
 * MmMatmasInbService
 * TODO
 */
public class MmMatmasInbService {
	private static final Logger log = Logger.getLogger(MmMatmasInbService.class);
	
	public void CreatedSync(JCO.ParameterList input, JCO.ParameterList tables, JCO.ParameterList output, String structureOrTableName) throws Exception {
		List<MmMatmasInb> lst_object = new ArrayList<MmMatmasInb>();
		JCO.Table table = tables.getTable(structureOrTableName);
		List<MmMatmasInb> lst = null;
		int records = -1;
		EntityManager em = null;
		String instance_no = null;
		try{
			
			records = table.getNumRows();
			em = new SessionEntityManager().CreatedEntityManager();
			MmMatmasInbServices MmMatmasInbServ = new MmMatmasInbServices(em);
			instance_no = MmMatmasInbServ.GetNewInstanceNo();
			
			for(int i = 0; i < records; i++)
			{
				System.out.println("i ="+ i + ", ARTICLE_CODE : " + table.getString("ARTICLE_CODE"));
				
				table.setRow(i);			
				MmMatmasInb model = new MmMatmasInb();
				model.setInstanceNo(instance_no);
				model.setArticleCode(CommonService.IsNullRNull(table.getString("ARTICLE_CODE")));
				model.setDescription(CommonService.IsNullRNull(table.getString("DESCRIPTION")));
				model.setDescriptionTh(CommonService.IsNullRNull(table.getString("DESCRIPTION_TH")));
				model.setCreatedOn(CommonService.IsNullRNull(table.getString("CREATED_ON")));
				model.setCreatedBy(CommonService.IsNullRNull(table.getString("CREATED_BY")));
				model.setUpdatedOn(CommonService.IsNullRNull(table.getString("LAST_UPD_ON")));
				model.setUpdatedBy(CommonService.IsNullRNull(table.getString("LAST_UPD_BY")));
				
				if(CommonService.IsNull(table.getString("ITEM_TYPE")))
					model.setItemType("NN");
				else
					model.setItemType(CommonService.IsNullRNull(table.getString("ITEM_TYPE")));
				
				model.setArtiTypeCode(CommonService.IsNullRNull(table.getString("ARTICLE_TYPE_CODE")));
				model.setArtiTypeName(CommonService.IsNullRNull(table.getString("ARTICLE_TYPE_NAME")));
				model.setArtiGrpCode(CommonService.IsNullRNull(table.getString("ARTICLE_GROUP_CODE")));
				model.setArtiGrpName(CommonService.IsNullRNull(table.getString("ARTICLE_GROUP_NAME")));
				model.setUm(CommonService.IsNullRNull(table.getString("UM")));				
				model.setStatus(CommonService.IsNullRNull(table.getString("STATUS")));
								
				//SAP Company
				model.setSapCompanyCode(CommonService.IsNullRNull(table.getString("COMPANY")));
				
				//SAP Plant Code
				model.setSapPlantCode(CommonService.IsNullRNull(table.getString("PROJECT_PLANT_CODE")));
				
				model.setLeadtime(new BigDecimal(CommonService.IsNullRZero(table.getString("LEADTIME"))));
				model.setArtiSubGrpCode(CommonService.IsNullRNull(table.getString("ARTICLE_SUB_GROUP_CODE")));
				model.setArtiSubGrpName(CommonService.IsNullRNull(table.getString("ARTICLE_SUB_GROUP_NAME")));
				model.setSeqNo(new BigDecimal(CommonService.IsNullRZero(table.getString("SEQ_NO"))));
				model.setPrFlag(CommonService.IsNullRNull(table.getString("PR_FLAG")));
				
				model.setExtRefKey(CommonService.IsNullRNull(table.getString("SYNC_EXTERNAL_REF_KEY")));
				model.setExtRefNo(CommonService.IsNullRNull(table.getString("SYNC_EXTERNAL_REF_NO")));
				model.setSyncCreatedby(CommonService.IsNullRNull(table.getString("SYNC_CREATEDBY")));
				model.setSyncUpdatedby(CommonService.IsNullRNull(table.getString("SYNC_UPDATEDBY")));
				model.setIssync(CommonService.IsNullRNull(table.getString("SYNC_ISSYNC")));
								
				model.setProductType(CommonService.IsNullRNull(table.getString("PRODUCT_TYPE")));
				model.setProductCode(CommonService.IsNullRNull(table.getString("PRODUCT_CODE")));
				model.setModelCode(CommonService.IsNullRNull(table.getString("MODEL_CODE")));
				model.setBrandName(CommonService.IsNullRNull(table.getString("BRAND_NAME")));
				model.setMaterialType(CommonService.IsNullRNull(table.getString("MATERIAL_TYPE")));
				model.setProductColor(CommonService.IsNullRNull(table.getString("PRODUCT_COLOR")));
				model.setProductSize(CommonService.IsNullRNull(table.getString("PRODUCT_SIZE")));
				model.setInstalllocation(CommonService.IsNullRNull(table.getString("INSTALL_LOCATION")));
				model.setProductdetail(CommonService.IsNullRNull(table.getString("PRODUCT_DETAILS")));
				model.setManufactures(CommonService.IsNullRNull(table.getString("MANUFACTURES")));
				model.setPicturepath(CommonService.IsNullRNull(table.getString("PICTURE_PATH")));				
				
				//Set Txn Reacord
				model.setCreatedOn(CommonService.IsNullRNull(table.getString("CREATED_ON")));
				model.setCreatedBy(CommonService.IsNullRNull(table.getString("CREATED_BY")));
				model.setUpdatedOn(CommonService.IsNullRNull(table.getString("LAST_UPD_ON")));
				model.setUpdatedBy(CommonService.IsNullRNull(table.getString("LAST_UPD_BY")));
				
				if(CommonService.IsNull(table.getString("LAST_UPD_ON")))
					model.setActionHandle(ACTION_HANDLER.INSERTED.toString());
				else 
					model.setActionHandle(ACTION_HANDLER.UPDATED.toString());
				
				//Set SAP External Key link
				model.setExtRefKey(CommonService.IsNullRNull(table.getString("SYNC_EXTERNAL_REF_KEY")));
				model.setExtRefNo(CommonService.IsNullRNull(table.getString("SYNC_EXTERNAL_REF_NO")));
				
				model.setInterfaceNo("MM-M2-010");
				
				lst_object.add(model);
			}
			
			MmMatmasInbServ.Inserted(lst_object);
						
			//Find Matrial in to Staging Table 
			lst = MmMatmasInbServ.findByInstanceNo(instance_no);									
			
			if(CommonService.getSize(lst) == records && CommonService.getSize(lst) > 0)
			{				
				List<MmMatmasInb> newList = new ArrayList<MmMatmasInb>();
				for(MmMatmasInb model : lst){
					
					//Company Validated
					if(CommonService.IsNull(model.getSapCompanyCode()))
						throw new Exception("Company is require field.");
					else{
						Company company = new CompanyAction().FindBySapCompany(model.getSapCompanyCode());
						if(CommonService.IsNull(company))
							throw new Exception("Data not found SAP Company=" + model.getSapCompanyCode() + " !!!");
						else
							model.setCompanyCode(company.getCompany());
					}
					
					//Project Validated
					if(CommonService.IsNull(model.getSapPlantCode()))
						throw new Exception("SapPlantCode is require field.");
					else{
						CostProject project = new ProjectAction().findPlantByCode(model.getSapPlantCode());
						if(CommonService.IsNull(project))
							throw new Exception("Data not found SapPlantCode=" + model.getSapPlantCode() + " !!!");
						else
							model.setProjectCode(project.getId().getProject());
					}
										
					newList.add(model);					
				}
				
				MmMatmasInbServ.Updated(newList);
				lst = MmMatmasInbServ.findByInstanceNo(instance_no);
				
				//Create Matrial to PROMIS
				new CostArticleAction().Processing(lst);
				
				for(int i = 0; i < records; i++)
				{
					MmMatmasInb obj = lst.get(i);
					table.setRow(i);
					table.setValue(CommonService.IsNullRString(obj.getPromisStagingId()), "PROMIS_TXN_ID");
					table.setValue("S", "MSG_CODE");
					table.setValue("Success", "MSG_DESC");
					table.setValue("SAP NO =" + obj.getExtRefNo(), "MSG_ALT_DESC");
					table.setValue("", "MSG_ACTION_RESULT");	
					log.info(CommonJCOReturn.toString(table));
				}
			}else{
				System.out.println("find not found  instance no = " + instance_no);
				log.info("find not found  instance no = " + instance_no);
			}				
		}
		catch(Exception e)
		{	
			System.out.println(e.getMessage());
			log.error(e.getMessage());
			
			if(!CommonService.IsNull(lst)){
				
				List<MmMatmasInb> newList = new ArrayList<MmMatmasInb>();
				for(MmMatmasInb model : lst){
					model.setIssync("N");
					model.setMsgCode("E");
					model.setMsgDesc(CommonService.CutString(e.getMessage(), 3500));
					model.setMsgAltDesc(CommonService.CutString(e.getMessage(), 3500));
					newList.add(model);					
				}
				
				//Update to DB
				new MmMatmasInbServices(em).Updated(newList);
				lst = new MmMatmasInbServices(em).findByInstanceNo(instance_no);
								
				if(CommonService.getSize(lst) == records && CommonService.getSize(lst) > 0){
					for(int i = 0; i < records; i++)
					{
						MmMatmasInb obj = lst.get(i);
						table.setRow(i);
						table.setValue(CommonService.IsNullRString(obj.getPromisStagingId()), "PROMIS_TXN_ID");
						table.setValue("E", "MSG_CODE");
						table.setValue(e.getMessage(), "MSG_DESC");
						table.setValue("SAP NO =" + obj.getExtRefNo(), "MSG_ALT_DESC");
						table.setValue("", "MSG_ACTION_RESULT");
						log.info(CommonJCOReturn.toString(table));
					}
				}
			}else{			
				for(int i = 0; i < records; i++)
				{
					table.setRow(i);
					table.setValue("E", "MSG_CODE");
					table.setValue(e.getMessage(), "MSG_DESC");
				}
			}
		}
	}
}
